import 'dart:io';

import 'package:flutter/material.dart';
import 'package:google_mlkit_translation/google_mlkit_translation.dart';

class ModelManagerView extends StatefulWidget {
  @override
  ModelManagerViewState createState() => ModelManagerViewState();
}

class ModelManagerViewState extends State<ModelManagerView> {
  final OnDeviceTranslatorModelManager _modelManager =
      OnDeviceTranslatorModelManager();
  final TextEditingController _modelNameController =
      TextEditingController(text: 'mobilenetv2.ms');
  final TextEditingController _serverUrlController =
      TextEditingController(text: 'http://10.50.40.168:3000/download/');
  String _status = '';
  bool _isWifiRequired = true;
  String model = TranslateLanguage.english.bcpCode;

  Future<void> _downloadModel() async {
    setState(() {
      _status = 'Downloading model...';
    });

    try {
      // 根据平台设置参数
      String? url;
      if (Platform.isOhos) {
        model = _modelNameController.text.trim();
        url = '${_serverUrlController.text.trim()}$model';
        _status += '\nUsing server URL: $url';
        print('GoogleMlKitCommons:: ModelManagerViewState url: $url');
      }

      final bool result = await _modelManager.downloadModel(
        model,
        isWifiRequired: _isWifiRequired,
        url: url,
      );

      if (result) {
        setState(() {
          _status += '\nModel downloaded successfully!';
        });
      } else {
        setState(() {
          _status += '\nFailed to download model.';
        });
      }
    } catch (e) {
      setState(() {
        _status += '\nError: $e';
      });
    }
  }

  Future<void> _checkModelStatus() async {
    setState(() {
      _status = 'Checking model status...';
    });

    try {
      final bool isDownloaded = await _modelManager
          .isModelDownloaded(model);

      setState(() {
        _status +=
            '\nModel is ${isDownloaded ? 'downloaded' : 'not downloaded'}';
      });
    } catch (e) {
      setState(() {
        _status += '\nError: $e';
      });
    }
  }

  Future<void> _deleteModel() async {
    setState(() {
      _status = 'Deleting model...';
    });

    try {
      final bool result =
          await _modelManager.deleteModel(model);

      if (result) {
        setState(() {
          _status += '\nModel deleted successfully!';
        });
      } else {
        setState(() {
          _status += '\nFailed to delete model.';
        });
      }
    } catch (e) {
      setState(() {
        _status += '\nError: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Model Manager Demo'),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Model Manager Example',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 20),
            TextField(
              controller: _modelNameController,
              decoration: const InputDecoration(
                labelText: 'Model Name',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            CheckboxListTile(
              title: const Text('Require Wi-Fi'),
              value: _isWifiRequired,
              onChanged: (value) {
                setState(() {
                  _isWifiRequired = value ?? true;
                });
              },
            ),
            const SizedBox(height: 16),
            if (Platform.isOhos)
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children:
                  [
                  TextField(
                    controller: _serverUrlController,
                    decoration: const InputDecoration(
                      labelText: 'Server URL (OHOS only)',
                      border: OutlineInputBorder(),
                    ),
                  ),
                  const SizedBox(height: 8),
                  const Text(
                    'This URL is used only on OHOS platform to specify the server address for model download.',
                    style: TextStyle(fontSize: 12, color: Colors.grey),
                  ),
                  const SizedBox(height: 16),
                ],
              ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _checkModelStatus,
              child: const Text('Check Model Status'),
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: _downloadModel,
              child: const Text('Download Model'),
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: _deleteModel,
              child: const Text('Delete Model'),
            ),
            const SizedBox(height: 20),
            const Text(
              'Status:',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 10),
            Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey),
                borderRadius: BorderRadius.circular(5),
              ),
              child: Text(_status),
            ),
          ],
        ),
      ),
    );
  }
}
